package com.stephen.mymall.handler;

import com.stephen.mymall.entity.vo.Result;
import com.stephen.mymall.enums.ResultEnum;
import com.stephen.mymall.exception.ResultException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * @ author: stephen
 * @ create: 2020-03-17 22:33
 * @ description: 全局异常处理
 **/
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 自定义异常
     * @param
     * @param request
     * @return
     */
    @ExceptionHandler(value = ResultException.class)
    public Result<Object> resultException(ResultException e, HttpServletRequest request) {
        log.error("接口{}的{}方法发生异常",request.getServletPath(),request.getMethod());
        log.error("自定义异常,{}",e.getMessage());
        return Result.result(e.getCode(),e.getMessage(),e.getData());
    }

    /**
     * validation 参数校验异常
     * @param
     * @return
     */
    @ExceptionHandler(value = {BindException.class,MethodArgumentNotValidException.class})
    public Result<Object> bindException(Exception e) {
        BindingResult bindingResult = null;
        if (e instanceof BindException) { // Form表单提交的参数是BindException
            bindingResult = ((BindException) e).getBindingResult();
        } else if (e instanceof MethodArgumentNotValidException) { // JSON提交的参数是MethodArgumentNotValidException
            bindingResult = ((MethodArgumentNotValidException)e).getBindingResult();
        }
        String field = bindingResult.getFieldError().getField();
        String errorMsg = bindingResult.getFieldError().getDefaultMessage();
        log.error("参数校验异常,{}",field + " " + errorMsg);
        return Result.result(ResultEnum.INVALID_PARAMS,field + " " + errorMsg);
    }

    /**
     * 一般异常
     * @param request
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    public Result<Object> commonException(Exception e,HttpServletRequest request) {
        log.error("接口{}的{}方法发生异常",request.getServletPath(),request.getMethod());
        return Result.error(ResultEnum.SYSTEM_ERROR,e.getMessage());
    }

}
